//
//  HomeViewController.swift
//  WBSwift
//
//  Created by 贺瑞 on 2017/6/24.
//  Copyright © 2017年 herui. All rights reserved.
//

import UIKit
import SnapKit
import MJRefresh

class HomeViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!

    var popoverManager : PopoverPresentationManager?
    
    
    lazy var data : [TimelineInfo] = [TimelineInfo]()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        loadData()
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(loadData))
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        tableView.mj_header.beginRefreshing()
        
    }
    
    
    
    
    
}

extension HomeViewController {
    func loadData() {
        
        let param = ["access_token" : UserInfo.userInfo()?.accessToken ?? "",
                     "since_id" : data.first?.id ?? 0] as [String : Any]
        NetWorkTools.get(url: HomeTimelineURL, params: param) { (resp, error) in
            self.tableView.mj_header.endRefreshing()
            
            guard error == nil else {
                HHLog(error)
                return
            }
            guard let result = (resp as? Dictionary<String, Any>) else {
                return
            }
            guard let list = (result["statuses"]) as? Array<Dictionary<String, Any>> else {
                return
            }
            
            var tempArray = [TimelineInfo]()

            for keyvalus in list {
                tempArray.append(TimelineInfo(keyvalues: keyvalus))
            }
            
            self.data = tempArray + self.data
            self.tableView.reloadData()
        }
        
    }

    func loadMoreData() {
        let param = ["access_token" : UserInfo.userInfo()?.accessToken ?? "",
                     "max_id" : self.data.last?.id ?? 0] as [String : Any]
        NetWorkTools.get(url: HomeTimelineURL, params: param) { (resp, error) in
            
            guard error == nil else {
                HHLog(error)
                return
            }
            guard let result = (resp as? Dictionary<String, Any>) else {
                return
            }
            guard let list = (result["statuses"]) as? Array<Dictionary<String, Any>> else {
                return
            }
            
            for keyvalus in list {
                
                let info = TimelineInfo(keyvalues: keyvalus)
                if(info.id != self.data.last?.id){
                    self.data.append(TimelineInfo(keyvalues: keyvalus))
                    self.tableView.mj_footer.endRefreshing()
                }else{
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                }
            }
            self.tableView.reloadData()
        }

    }

    
    
}
extension HomeViewController {
    func setupUI() {
        
        tableView.register(UINib(nibName: "HomeTimelineCell", bundle: nil), forCellReuseIdentifier: "HomeTimelineCell")
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        
        let btn = UIButton(imageName: "tabbar_compose_icon_add", bgImageName: "tabbar_compose_button")
        btn.addTarget(self, action: #selector(compostBtnOnclick), for: .touchUpInside)
        tabBarController?.tabBar.addSubview(btn)
        btn.snp.makeConstraints { (make : ConstraintMaker) in
            make.center.equalTo(btn.superview!)
        }
        
        
        if !(UserInfo.userInfo()?.isLogin ?? false) {
            setupVisitorView()
        }
        
        //导航栏
        let leftBtn = UIButton(imageName: "navigationbar_friendattention")
        leftBtn.addTarget(self, action:#selector(leftBtnOnclick), for: .touchUpInside)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
        
        let rightBtn = UIButton(imageName: "navigationbar_pop")
        rightBtn.addTarget(self, action:#selector(rightBtnOnclick), for: .touchUpInside)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        let titleBtn = UIButton(imageName: "navigationbar_arrow_down")
        titleBtn.setImage(UIImage(named: "navigationbar_arrow_up"), for: .selected)
        titleBtn.setTitle(" Hello Swift", for: .normal)
        titleBtn.setTitleColor(UIColor.black, for: .normal)
        titleBtn.addTarget(self, action:#selector(titleBtnOnclick(btn:)), for: .touchUpInside)
        titleBtn.sizeToFit()
        navigationItem.titleView = titleBtn
    }

    //访客视图
    func setupVisitorView() {
        
        let visitorV = VisitorView.visitorView()
        view.addSubview(visitorV)
        visitorV.snp.makeConstraints { (make : ConstraintMaker) in
            make.edges.equalTo(visitorV.superview!)
        }
        visitorV.loginBlock = {()->() in
            //
            let webVC = OAuthViewController(url: OAuthURL)
            let nav = UINavigationController(rootViewController: webVC)
            self.present(nav, animated: true, completion: nil)
        }
        visitorV.registerBlock = {()->() in
            
        }

    }
    
}


extension HomeViewController {
    //MARK: 发布微博
    func compostBtnOnclick() {
//        let nav = UINavigationController(rootViewController: ComposeViewController())
        present(ComposeViewController(), animated: true, completion: nil)
    }

    
    func leftBtnOnclick() {
        HHLog("leftBtnOnclick")
    }
    func rightBtnOnclick() {
        HHLog("rightBtnOnclick")
        
        print(UserInfo.userInfo() ?? "")
    }
    func titleBtnOnclick(btn : UIButton) {

        btn.isSelected = !btn.isSelected
        
        let popVC = PopoverViewController()

        popoverManager = PopoverPresentationManager(presentedViewController: popVC, presenting: self)
        
        popoverManager?.block = {(forPresent)->() in
            btn.isSelected = forPresent
        }
        
        popVC.transitioningDelegate = popoverManager;
        popVC.modalPresentationStyle = .custom
        
        present(popVC, animated: true, completion: nil)
    }
    
}


extension HomeViewController : UITableViewDelegate, UITableViewDataSource {
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTimelineCell", for: indexPath) as! HomeTimelineCell
        cell.model = data[indexPath.row]
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("点击了\(indexPath.row)")
    }

    
}

